<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\BaseController;
use app\common\lib\Show;
use app\common\lib\Time;
use think\facade\Request;
use app\common\business\User as BusiUser;

class User extends BaseController
{
    /**
     * 获取用户信息
     *
     * @return \think\response\Json
     */
    public function index()
    {
        $id = (int) Request::header('userId');
        if (!$id) return Show::error();
        $busiUser = new BusiUser();
        try {
            $userInfo = $busiUser->getNormalUserById($id);
        } catch (\Exception $e) {
            return [];
        }
        $result = [
            'id'       => $id,
            'username' => $userInfo['username'],
            'phone'    => $userInfo['phone'],
            'sex'      => $userInfo['sex'],
        ];
        return Show::success($result);
    }

    /**
     * 用户信息修改
     *
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update()
    {
        $userId = intval(Request::header('userId'));
        $token = Request::header('access-token');
        $username = Request::header('username');
        $data   = [
            'username' => Request::param('username', '', 'trim'),
            'sex'      => Request::param('sex', 1, 'intval'),
            'operate_user' => $username,
        ];

        // 提交数据验证
        $validate = new \app\api\validate\User();
        if (!$validate->scene('update')->check($data)) {
            return Show::error($validate->getError());
        }

        $busiUser = new BusiUser();
        $result   = $busiUser->updateUserById($userId, $data);
        if ($result) {
            $userInfo = cache(config('redis.token.prefix').$token);
            $userInfo['username'] = $data['username'];
            cache(config('redis.token.prefix').$token, $userInfo, Time::userLoginExpiresTime($userInfo['type']));
            return Show::success();
        }
        return Show::error('更新失败');
    }
}
